package com.alipay.api;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayMobilePublicMultiMediaDownloadRequest;
import com.alipay.api.AlipayMobilePublicMultiMediaDownloadResponse;
import com.alipay.api.AlipayRequest;
import com.alipay.api.AlipayResponse;
import com.alipay.api.internal.parser.json.ObjectJsonParser;
import com.alipay.api.internal.util.AlipayHashMap;
import com.alipay.api.internal.util.AlipayLogger;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.internal.util.RequestParametersHolder;
import com.alipay.api.internal.util.StreamUtil;
import com.alipay.api.internal.util.StringUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.Map.Entry;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class AlipayMobilePublicMultiMediaClient implements AlipayClient {

   private static final String DEFAULT_CHARSET = "UTF-8";
   private static final String METHOD_POST = "POST";
   private static final String METHOD_GET = "GET";
   private String serverUrl;
   private String appId;
   private String privateKey;
   private String prodCode;
   private String format;
   private String sign_type;
   private String charset;
   private int connectTimeout;
   private int readTimeout;


   public AlipayMobilePublicMultiMediaClient(String serverUrl, String appId, String privateKey) {
      this.format = "json";
      this.sign_type = "RSA";
      this.connectTimeout = 3000;
      this.readTimeout = 15000;
      this.serverUrl = serverUrl;
      this.appId = appId;
      this.privateKey = privateKey;
   }

   public AlipayMobilePublicMultiMediaClient(String serverUrl, String appId, String privateKey, String format) {
      this(serverUrl, appId, privateKey);
      this.format = format;
   }

   public AlipayMobilePublicMultiMediaClient(String serverUrl, String appId, String privateKey, String format, String charset) {
      this(serverUrl, appId, privateKey);
      this.format = format;
      this.charset = charset;
   }

   public AlipayResponse execute(AlipayRequest request) throws AlipayApiException {
      return this.execute(request, (String)null);
   }

   public AlipayResponse execute(AlipayRequest request, String accessToken) throws AlipayApiException {
      return this._execute(request, accessToken);
   }

   private AlipayResponse _execute(AlipayRequest request, String authToken) throws AlipayApiException {
      return this.doGet(request);
   }

   public AlipayResponse doGet(AlipayRequest request) throws AlipayApiException {
      if(StringUtils.isEmpty(this.charset)) {
         this.charset = "UTF-8";
      }

      RequestParametersHolder requestHolder = new RequestParametersHolder();
      AlipayHashMap appParams = new AlipayHashMap(request.getTextParams());
      requestHolder.setApplicationParams(appParams);
      AlipayHashMap protocalMustParams = new AlipayHashMap();
      protocalMustParams.put("method", request.getApiMethodName());
      protocalMustParams.put("version", request.getApiVersion());
      protocalMustParams.put("app_id", this.appId);
      protocalMustParams.put("sign_type", this.sign_type);
      protocalMustParams.put("charset", this.charset);
      Long timestamp = Long.valueOf(System.currentTimeMillis());
      SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      df.setTimeZone(TimeZone.getTimeZone("GMT+8"));
      protocalMustParams.put("timestamp", df.format(new Date(timestamp.longValue())));
      protocalMustParams.put("format", this.format);
      requestHolder.setProtocalMustParams(protocalMustParams);
      String signContent = AlipaySignature.getSignatureContent(requestHolder);
      protocalMustParams.put("sign", AlipaySignature.rsaSign(signContent, this.privateKey, this.charset));
      AlipayMobilePublicMultiMediaDownloadResponse rsp = null;

      try {
         if(request instanceof AlipayMobilePublicMultiMediaDownloadRequest) {
            OutputStream e = ((AlipayMobilePublicMultiMediaDownloadRequest)request).getOutputStream();
            rsp = doGet(this.serverUrl, requestHolder, this.charset, this.connectTimeout, this.readTimeout, e);
         }

         return rsp;
      } catch (IOException var10) {
         throw new AlipayApiException(var10);
      }
   }

   public static AlipayMobilePublicMultiMediaDownloadResponse doGet(String url, RequestParametersHolder requestHolder, String charset, int connectTimeout, int readTimeout, OutputStream output) throws AlipayApiException, IOException {
      HttpURLConnection conn = null;
      AlipayMobilePublicMultiMediaDownloadResponse response = null;

      AlipayMobilePublicMultiMediaDownloadResponse var16;
      try {
         TreeMap params = new TreeMap();
         AlipayHashMap appParams = requestHolder.getApplicationParams();
         if(appParams != null && appParams.size() > 0) {
            params.putAll(appParams);
         }

         AlipayHashMap protocalMustParams = requestHolder.getProtocalMustParams();
         if(protocalMustParams != null && protocalMustParams.size() > 0) {
            params.putAll(protocalMustParams);
         }

         AlipayHashMap protocalOptParams = requestHolder.getProtocalOptParams();
         if(protocalOptParams != null && protocalOptParams.size() > 0) {
            params.putAll(protocalOptParams);
         }

         String ctype = "application/x-www-form-urlencoded;charset=" + charset;
         String query = buildQuery(params, charset);

         Map map;
         try {
            conn = getConnection(buildGetUrl(url, query), "GET", ctype);
            conn.setConnectTimeout(connectTimeout);
            conn.setReadTimeout(readTimeout);
         } catch (IOException var21) {
            map = getParamsFromUrl(url);
            AlipayLogger.logCommError(var21, url, (String)map.get("app_key"), (String)map.get("method"), (Map)params);
            throw var21;
         }

         try {
            if(conn.getResponseCode() != 200) {
               response = new AlipayMobilePublicMultiMediaDownloadResponse();
               response.setCode(String.valueOf(conn.getResponseCode()));
               response.setMsg(conn.getResponseMessage());
               response.setParams(appParams);
               return response;
            }

            if(conn.getContentType() == null || !conn.getContentType().toLowerCase().contains("text/plain")) {
               StreamUtil.io(conn.getInputStream(), output);
               response = new AlipayMobilePublicMultiMediaDownloadResponse();
               response.setCode("200");
               response.setMsg("成功");
               response.setBody("{\"alipay_mobile_public_multimedia_download_response\":{\"code\":200,\"msg\":\"成功\"}}");
               response.setParams(appParams);
               return response;
            }

            String e = getResponseAsString(conn);
            ObjectJsonParser map1 = new ObjectJsonParser(AlipayMobilePublicMultiMediaDownloadResponse.class);
            response = (AlipayMobilePublicMultiMediaDownloadResponse)map1.parse(e);
            response.setBody(e);
            response.setParams(appParams);
            var16 = response;
         } catch (IOException var22) {
            map = getParamsFromUrl(url);
            AlipayLogger.logCommError(var22, conn, (String)map.get("app_key"), (String)map.get("method"), (Map)params);
            throw var22;
         }
      } finally {
         if(conn != null) {
            conn.disconnect();
         }

         if(output != null) {
            output.close();
         }

      }

      return var16;
   }

   private static HttpURLConnection getConnection(URL url, String method, String ctype) throws IOException {
      Object conn = null;
      if("https".equals(url.getProtocol())) {
         SSLContext ctx = null;

         try {
            ctx = SSLContext.getInstance("TLS");
            ctx.init(new KeyManager[0], new TrustManager[]{new AlipayMobilePublicMultiMediaClient.DefaultTrustManager(null)}, new SecureRandom());
         } catch (Exception var6) {
            throw new IOException(var6);
         }

         HttpsURLConnection connHttps = (HttpsURLConnection)url.openConnection();
         connHttps.setSSLSocketFactory(ctx.getSocketFactory());
         connHttps.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
               return false;
            }
         });
         conn = connHttps;
      } else {
         conn = (HttpURLConnection)url.openConnection();
      }

      ((HttpURLConnection)conn).setRequestMethod(method);
      ((HttpURLConnection)conn).setDoInput(true);
      ((HttpURLConnection)conn).setDoOutput(true);
      ((HttpURLConnection)conn).setRequestProperty("Accept", "text/xml,text/javascript,text/html");
      ((HttpURLConnection)conn).setRequestProperty("User-Agent", "aop-sdk-java");
      ((HttpURLConnection)conn).setRequestProperty("Content-Type", ctype);
      return (HttpURLConnection)conn;
   }

   protected static String getResponseAsString(HttpURLConnection conn) throws IOException {
      String charset = getResponseCharset(conn.getContentType());
      InputStream es = conn.getErrorStream();
      if(es == null) {
         return getStreamAsString(conn.getInputStream(), charset);
      } else {
         String msg = getStreamAsString(es, charset);
         if(StringUtils.isEmpty(msg)) {
            throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
         } else {
            throw new IOException(msg);
         }
      }
   }

   private static String getStreamAsString(InputStream stream, String charset) throws IOException {
      try {
         BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset));
         StringWriter writer = new StringWriter();
         char[] chars = new char[256];
         boolean count = false;

         int count1;
         while((count1 = reader.read(chars)) > 0) {
            writer.write(chars, 0, count1);
         }

         String var6 = writer.toString();
         return var6;
      } finally {
         if(stream != null) {
            stream.close();
         }

      }
   }

   private static String getResponseCharset(String ctype) {
      String charset = "UTF-8";
      if(!StringUtils.isEmpty(ctype)) {
         String[] params = ctype.split(";");
         String[] arr$ = params;
         int len$ = params.length;

         for(int i$ = 0; i$ < len$; ++i$) {
            String param = arr$[i$];
            param = param.trim();
            if(param.startsWith("charset")) {
               String[] pair = param.split("=", 2);
               if(pair.length == 2 && !StringUtils.isEmpty(pair[1])) {
                  charset = pair[1].trim();
               }
               break;
            }
         }
      }

      return charset;
   }

   private static Map getParamsFromUrl(String url) {
      Object map = null;
      if(url != null && url.indexOf(63) != -1) {
         map = splitUrlQuery(url.substring(url.indexOf(63) + 1));
      }

      if(map == null) {
         map = new HashMap();
      }

      return (Map)map;
   }

   private static URL buildGetUrl(String strUrl, String query) throws IOException {
      URL url = new URL(strUrl);
      if(StringUtils.isEmpty(query)) {
         return url;
      } else {
         if(StringUtils.isEmpty(url.getQuery())) {
            if(strUrl.endsWith("?")) {
               strUrl = strUrl + query;
            } else {
               strUrl = strUrl + "?" + query;
            }
         } else if(strUrl.endsWith("&")) {
            strUrl = strUrl + query;
         } else {
            strUrl = strUrl + "&" + query;
         }

         return new URL(strUrl);
      }
   }

   public static String buildQuery(Map params, String charset) throws IOException {
      if(params != null && !params.isEmpty()) {
         StringBuilder query = new StringBuilder();
         Set entries = params.entrySet();
         boolean hasParam = false;
         Iterator i$ = entries.iterator();

         while(i$.hasNext()) {
            Entry entry = (Entry)i$.next();
            String name = (String)entry.getKey();
            String value = (String)entry.getValue();
            if(StringUtils.areNotEmpty(new String[]{name, value})) {
               if(hasParam) {
                  query.append("&");
               } else {
                  hasParam = true;
               }

               query.append(name).append("=").append(URLEncoder.encode(value, charset));
            }
         }

         return query.toString();
      } else {
         return null;
      }
   }

   public static Map splitUrlQuery(String query) {
      HashMap result = new HashMap();
      String[] pairs = query.split("&");
      if(pairs != null && pairs.length > 0) {
         String[] arr$ = pairs;
         int len$ = pairs.length;

         for(int i$ = 0; i$ < len$; ++i$) {
            String pair = arr$[i$];
            String[] param = pair.split("=", 2);
            if(param != null && param.length == 2) {
               result.put(param[0], param[1]);
            }
         }
      }

      return result;
   }

   static {
      Security.setProperty("jdk.certpath.disabledAlgorithms", "");
   }

   private static class DefaultTrustManager implements X509TrustManager {

      private DefaultTrustManager() {}

      public X509Certificate[] getAcceptedIssuers() {
         return null;
      }

      public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}

      public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}

      // $FF: synthetic method
      DefaultTrustManager(Object x0) {
         this();
      }
   }
}
